package br.com.hsp.system.beans;

import java.util.List;
import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;

import br.com.hsp.system.repository.GerenteARSRepository; 
import br.com.hsp.users.GerenteARS;

@ManagedBean
public class GerenteARSBean {

	private	GerenteARS gerenteARS = new GerenteARS();
	
	private List<GerenteARS> gerenteARSs; 

	public void add() {
		EntityManager manager = this.getManager();
		GerenteARSRepository gerenteARSRepository = new GerenteARSRepository(manager);

		if (this.gerenteARS.getId() == null) {
			gerenteARSRepository.add(this.gerenteARS);
		} else {
			gerenteARSRepository.atualiza(this.gerenteARS);
		}
		this.gerenteARS = new GerenteARS();
	}

	public void preparaAlteracao() {
		Map<String, String> params = FacesContext.getCurrentInstance()
				.getExternalContext().getRequestParameterMap();
		Long id = Long.parseLong(params.get("id"));
		EntityManager manager = this.getManager();
		GerenteARSRepository repository = new GerenteARSRepository(manager);
		this.gerenteARS = repository.procura(id);

	}
	

	public void remove() {
		Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		Long id = Long.parseLong(params.get("id"));
		EntityManager manager = this.getManager();
		GerenteARSRepository repository = new GerenteARSRepository(manager);
		repository.remove(id);
		this.gerenteARS = null;
		this.gerenteARSs = null;
	}
	

	private EntityManager getManager() {
		FacesContext fc = FacesContext.getCurrentInstance();
		ExternalContext ec = fc.getExternalContext();
		HttpServletRequest request = (HttpServletRequest) ec.getRequest();
		return (EntityManager) request.getAttribute("EntityManager");

	}

	public List<GerenteARS> getGerenteARSs() {
		if (this.gerenteARSs == null) {
			EntityManager manager = this.getManager();
			GerenteARSRepository repository = new GerenteARSRepository(manager);
			this.gerenteARSs = repository.getLista();
		}
		return this.gerenteARSs;
	}

	public GerenteARS getGerenteARS() {
		return gerenteARS;
	}

	public void setGerenteARS(GerenteARS gerenteARS) {
		this.gerenteARS = gerenteARS;
	}

}
